# -*- coding:utf-8 -*-
import hashlib, os
from fastapi import UploadFile

from utils.minio import MinioService
from io import BytesIO

async def get_file_info(filename: str):
    print(f"获取文件信息：{filename}")
    print(f"文件信息：{await MinioService().get_file_info(filename)}")
    print(f"文件信息：{await MinioService().get_url(filename)}")
    return await MinioService().get_file_info(filename)

async def save_file(file: UploadFile, path: str, content_type: str)->str:
    await file.seek(0)
    return await MinioService().upload(BytesIO(await file.read()), path, file.size, content_type)

async def merge_file(filename:str, path: str, content_type: str)->str:
    metadata = {'Content-Type': content_type}
    return await MinioService().compose_object(filename, path, metadata)

async def remove_file(filename: str):
    return await MinioService().remove_objects(filename)

async def calculate_object_md5(filename: str)->str:
    resp = await MinioService().get_object(filename)
    # 分块读取数据
    chunk_size = 1024*1024  # 每次读取的块大小（字节）
    # 初始化 MD5 哈希对象
    md5_hash = hashlib.md5()
    if resp is None: return None
    try:
        for chunk in resp.stream(chunk_size):  # 逐块读取数据
            md5_hash.update(chunk)
    finally:
        resp.release_conn()
    # 返回文件的 MD5 值
    return md5_hash.hexdigest()

async def save_file_local(file: UploadFile, path: str):
    file_dir = os.path.dirname(path)
    if not os.path.exists(file_dir):
        os.makedirs(file_dir)
    size = file.size
    save = 0
    with open(path, "wb") as buffer:
        await file.seek(0)
        while chunk := file.file.read(8192):  # 逐块读取文件
            buffer.write(chunk)
            save += len(chunk)
            print(f"已上传 {save}/{size} 字节: {save / size * 100:.2f}%")

    print(f"文件上传完成，保存路径为：{path}")


def calculate_md5(file: UploadFile) -> str:
    # 初始化 MD5 哈希对象
    md5_hash = hashlib.md5()
    
    # 读取文件内容并更新 MD5 哈希值
    while chunk := file.file.read(8192):  # 逐块读取文件
        # print(f"已读取 {len(chunk)} 字节")
        md5_hash.update(chunk)
    # 返回文件的 MD5 值
    return md5_hash.hexdigest()

def calculate_file_md5(file: bytes) -> str:
    # 初始化 MD5 哈希对象
    md5_hash = hashlib.md5()
    
    # 读取文件内容并更新 MD5 哈希值
    while chunk := file.read(8192):  # 逐块读取文件
        # print(f"已读取 {len(chunk)} 字节")
        md5_hash.update(chunk)
    # 返回文件的 MD5 值
    return md5_hash.hexdigest()
